package com.example.byexample

fun main() {
    // 范围函数

    // let 保留字
    val empty = "test".let {               // 1
        customPrint(it)                    // 2
        it.isEmpty()                       // 3
    }
    println(" is empty: $empty")
    printNonNull(null)
    printNonNull("my string")
    printIfBothNonNull("First", "Second")

    // run 和 let 一样，run 是标准库中的另一个作用域函数。
    getNullableLength(null)
    getNullableLength("")
    getNullableLength("some string with Kotlin")

    // with
//    with(configuration) {
//        println("$host:$port")
//    }

    // instead of:
    println("${configuration.host}:${configuration.port}")

}

fun getNullableLength(ns: String?) {
    println("for \"$ns\":")
    ns?.run {                                                  // 1
        println("\tis empty? " + isEmpty())                    // 2
        println("\tlength = $length")
        length                                                 // 3
    }
}

fun customPrint(str: String?) {
    println("$str")
}

fun printNonNull(str: String?) {
    println("Printing \"$str\":")

    str?.let {                         // 4
        print("\t")
        customPrint(it)
        println()
    }
}

fun printIfBothNonNull(strOne: String?, strTwo: String?) {
    strOne?.let { firstString ->       // 5
        strTwo?.let { secondString ->
            customPrint("$firstString : $secondString")
            println()
        }
    }
}